package com.pig4cloud.pig.module.controller.attendance;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.attendance.AttendanceGroup;
import com.pig4cloud.pig.module.api.entity.attendance.AttendanceGroupUser;
import com.pig4cloud.pig.module.api.entity.attendance.AttendanceWorkShift;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.property.Property;
import com.pig4cloud.pig.module.service.attendance.IAttendanceGroupService;
import com.pig4cloud.pig.module.service.attendance.IAttendanceGroupUserService;
import com.pig4cloud.pig.module.service.attendance.IAttendanceWorkShiftService;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import com.pig4cloud.pig.module.service.property.IPropertyUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 考勤组Controller
 *
 * @author ruoyi
 * @date 2022-09-20
 */
@Validated
@Api(value = "考勤组控制器", tags = {"考勤组管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/attendance/group")
public class AttendanceGroupController {

    private final IAttendanceGroupService attendanceGroupService;
    private final IEstateService estateService;
    private final IPropertyService propertyService;
    private final RemoteUserService remoteUserService;
    private final IAttendanceWorkShiftService workShiftService;
    private final IPropertyUserService propertyUserService;
    private final IAttendanceGroupUserService attendanceGroupUserService;

    /**
     * 查询考勤组列表
     */
    @ApiOperation("查询考勤组列表")
    @PreAuthorize("@pms.hasPermission('module:attendanceGroup:list')")
    @GetMapping("/list")
    public TableDataInfo<AttendanceGroup> list(@Validated AttendanceGroup attendanceGroup) {
		QueryWrapper<AttendanceGroup> qw = new QueryWrapper<>();
		if(attendanceGroup.getPropertyId() != null){
			qw.eq("property_id",attendanceGroup.getPropertyId());
		}
		if(attendanceGroup.getEstateId() != null){
			qw.eq("estate_id",attendanceGroup.getEstateId());
		}
		TableDataInfo<AttendanceGroup> td = PageUtils.buildDataInfo(attendanceGroupService.page(PageUtils.buildPage(),qw));
		List<AttendanceGroup> list = td.getData();
		for(AttendanceGroup list1:list){
			Integer w1 = list1.getWorkDay1();
			Integer w2 = list1.getWorkDay2();
			Integer w3 = list1.getWorkDay3();
			Integer w4 = list1.getWorkDay4();
			Integer w5 = list1.getWorkDay5();
			Integer w6 = list1.getWorkDay6();
			Integer w7 = list1.getWorkDay7();
			if(w1==1&&w2==1&&w3==1&&w4==1&&w5==1){
				if(w6==1 && w7==1){
					list1.setWorkSystem(0);
				}else if((w6==1 && w7==0)||(w6==0 && w7==1)){
					list1.setWorkSystem(1);
				}else if(w6==0 && w7==0){
					list1.setWorkSystem(2);
				}
			}else {
				list1.setWorkSystem(3);
			}
			if (list1.getEstateId()!=null){
				Estate estate=estateService.findById(list1.getEstateId());
				list1.setEstateName(estate.getEstateName());
			}else {
				list1.setEstateName("未绑定");
			}
			Property property=propertyService.findById(list1.getPropertyId());

			list1.setPropertyName(property.getPropertyName());
			if (list1.getWorkShift()!=null){
				AttendanceWorkShift attendanceWorkShift =workShiftService.findById(list1.getWorkShift());
				list1.setShiftName(attendanceWorkShift.getShiftName());
			}else {
				list1.setShiftName("未设置");
			}
		}
		return td;
    }

    /**
     * 导出考勤组列表
     */
    @ApiOperation("导出考勤组列表")
    @PreAuthorize("@pms.hasPermission('module:attendanceGroup:export')")
    @SysLog("考勤组")
    @GetMapping("/export")
    public List export(@Validated AttendanceGroup attendanceGroup) {
        List<AttendanceGroup> list = attendanceGroupService.list();
        // ExcelUtil<AttendanceGroup> util = new // ExcelUtil<AttendanceGroup>(AttendanceGroup.class);
        return list;// util.exportExcel(list, "考勤组");
    }

    /**
     * 获取考勤组详细信息
     */
    @ApiOperation("获取考勤组详细信息")
    @PreAuthorize("@pms.hasPermission('module:attendanceGroup:query')")
    @GetMapping("/{id}")
    public R<AttendanceGroup> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        AttendanceGroup attendanceGroup = attendanceGroupService.getById(id);
        QueryWrapper<AttendanceGroupUser> qw1 = new QueryWrapper<>();
        qw1.eq("group_id",attendanceGroup.getId());
        List<AttendanceGroupUser> list=attendanceGroupUserService.list(qw1);
        if (list != null){

            ArrayList<String> user=new ArrayList<>();

            for (AttendanceGroupUser list1:list){
                user.add(String.valueOf(list1.getSysUserId()));
            }

            String[] arrString = user.toArray(new String[list.size()]) ;
            attendanceGroup.setUserIds(arrString);
        }
        return R.ok(attendanceGroup);
    }

    /**
     * 新增考勤组
     */
    @ApiOperation("新增考勤组")
    @PreAuthorize("@pms.hasPermission('module:attendanceGroup:add')")
    @SysLog("考勤组")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody AttendanceGroup attendanceGroup) {
        if (attendanceGroup.getGroupName()!=null){
            AttendanceGroup group = attendanceGroupService.selectByUniqueColumn("group_name",attendanceGroup.getGroupName());
            if (group!=null){
                return R.failed("新建考勤组'" + attendanceGroup.getGroupName() + "'失败，组名已存在");
            }
        }
        if(attendanceGroup.getWorkSystem()!=null){
            if(attendanceGroup.getWorkSystem()!=3){
                attendanceGroup.setWorkDay1(1);
                attendanceGroup.setWorkDay2(1);
                attendanceGroup.setWorkDay3(1);
                attendanceGroup.setWorkDay4(1);
                attendanceGroup.setWorkDay5(1);
                if(attendanceGroup.getWorkSystem()==0){
                    attendanceGroup.setWorkDay6(1);
                    attendanceGroup.setWorkDay7(1);
                }else if(attendanceGroup.getWorkSystem()==2){
                    attendanceGroup.setWorkDay6(0);
                    attendanceGroup.setWorkDay7(0);
                }else {
                    if(attendanceGroup.getRest()==0){
                        attendanceGroup.setWorkDay6(1);
                        attendanceGroup.setWorkDay7(0);
                    }else if(attendanceGroup.getRest()==1){
                        attendanceGroup.setWorkDay6(0);
                        attendanceGroup.setWorkDay7(1);
                    }
                }
            }
        }
        Property property=propertyService.findById(attendanceGroup.getPropertyId());
        attendanceGroup.setPropertyName(property.getPropertyName());
        if (attendanceGroup.getEstateId()!=null){
            Estate estate=estateService.findById(attendanceGroup.getEstateId());
            attendanceGroup.setEstateName(estate.getEstateName());
        }else {
            attendanceGroup.setEstateName("未绑定小区");
        }
        boolean pd=attendanceGroupService.save(attendanceGroup);
        if (!pd){
            return R.failed("新建考勤组'" + attendanceGroup.getGroupName() + "'失败");
        }
        if (attendanceGroup.getUserIds()!=null){
//            String[] id = attendanceGroup.getUserIds().split(",");
            for (String userId:attendanceGroup.getUserIds()){
				R<UserInfo> userInfo = remoteUserService.userDetail(Long.valueOf(userId), SecurityConstants.FROM_IN);
				SysUser user = userInfo.getData().getSysUser();
               AttendanceGroupUser groupUser=new AttendanceGroupUser();
               if (user!=null){
                    groupUser.setGroupName(attendanceGroup.getGroupName());
                    groupUser.setPropertyId(attendanceGroup.getPropertyId());
                    groupUser.setPropertyName(attendanceGroup.getPropertyName());
                    if (attendanceGroup.getEstateId()!=null){
                        groupUser.setEstateId(attendanceGroup.getEstateId());
                        groupUser.setEstateName(attendanceGroup.getEstateName());
                    }else {
                        groupUser.setEstateName("未绑定小区");
                    }
                    groupUser.setUserId(0);
                    groupUser.setUserType(1);
                    groupUser.setSysUserId(user.getUserId());
                    groupUser.setState(1);
                    groupUser.setIsCheckHoliday(0);
                    QueryWrapper<AttendanceGroupUser> qw =new QueryWrapper<>();
                    qw.eq("sys_user_id",user.getUserId());
                    List<AttendanceGroupUser> user2=attendanceGroupUserService.list(qw);
                    if (user2!=null){
                        groupUser.setIsDefault(0);
                    }else {
                        groupUser.setIsDefault(1);
                    }
                    AttendanceGroup group1 = attendanceGroupService.selectByUniqueColumn("group_name",attendanceGroup.getGroupName());
                    groupUser.setGroupId(group1.getId());
                    if (attendanceGroup.getIsDefault()!=null){
                        groupUser.setIsDefault(attendanceGroup.getIsDefault());
                    }
                    boolean pd2=attendanceGroupUserService.save(groupUser);
                    if (pd2=false){
                        return R.failed("用户'" + groupUser.getSysUserId() + "'添加失败");
                    }
               }
            }
        }
        return R.okByRow(1);
    }

    /**
     * 修改考勤组
     */
    @ApiOperation("修改考勤组")
    @PreAuthorize("@pms.hasPermission('module:attendanceGroup:edit')")
    @SysLog("考勤组")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody AttendanceGroup attendanceGroup) {
        if(attendanceGroup.getWorkSystem()!=null){
            if(attendanceGroup.getWorkSystem()!=3){
                attendanceGroup.setWorkDay1(1);
                attendanceGroup.setWorkDay2(1);
                attendanceGroup.setWorkDay3(1);
                attendanceGroup.setWorkDay4(1);
                attendanceGroup.setWorkDay5(1);
                if(attendanceGroup.getWorkSystem()==0){
                    attendanceGroup.setWorkDay6(1);
                    attendanceGroup.setWorkDay7(1);
                }else if(attendanceGroup.getWorkSystem()==2){
                    attendanceGroup.setWorkDay6(0);
                    attendanceGroup.setWorkDay7(0);
                }else {
                    if(attendanceGroup.getRest()==0){
                        attendanceGroup.setWorkDay6(1);
                        attendanceGroup.setWorkDay7(0);
                    }else if(attendanceGroup.getRest()==1){
                        attendanceGroup.setWorkDay6(0);
                        attendanceGroup.setWorkDay7(1);
                    }
                }
            }
        }
        Property property=propertyService.findById(attendanceGroup.getPropertyId());
        attendanceGroup.setPropertyName(property.getPropertyName());
        if (attendanceGroup.getEstateId()!=null){
            Estate estate=estateService.findById(attendanceGroup.getEstateId());
            attendanceGroup.setEstateName(estate.getEstateName());
        }

        if (attendanceGroup.getUserIds()!=null){
            QueryWrapper<AttendanceGroupUser> qw1=new QueryWrapper<>();
            qw1.eq("group_id",attendanceGroup.getId());
            List<AttendanceGroupUser> list=attendanceGroupUserService.list(qw1);
            List<Integer> newList = new ArrayList<>();
            List<Integer> oldList = new ArrayList<>();
            for (String userId:attendanceGroup.getUserIds()){
                newList.add(Integer.valueOf(userId));
            }
            for (AttendanceGroupUser list1:list){
                oldList.add(Math.toIntExact(list1.getSysUserId()));
            }
            List<Integer> delList = new ArrayList<>(CollectionUtils.subtract(oldList, newList));
            List<Integer> addList = new ArrayList<>(CollectionUtils.subtract(newList, oldList));

            System.out.println("删除"+delList);
            System.out.println("添加"+addList);
            for (Integer list1:delList){
                QueryWrapper<AttendanceGroupUser> qw=new QueryWrapper<>();
                qw.eq("sys_user_id",list1);
                attendanceGroupUserService.remove(qw);
            }
            for (Integer userId : addList){
				R<UserInfo> userInfo = remoteUserService.userDetail(Long.valueOf(userId), SecurityConstants.FROM_IN);
				SysUser user = userInfo.getData().getSysUser();
                AttendanceGroupUser groupUser = new AttendanceGroupUser();
                if (user != null){
                    groupUser.setGroupName(attendanceGroup.getGroupName());
                    groupUser.setPropertyId(attendanceGroup.getPropertyId());
                    groupUser.setPropertyName(attendanceGroup.getPropertyName());
                    if (attendanceGroup.getEstateId() != null){
                        groupUser.setEstateId(attendanceGroup.getEstateId());
                        groupUser.setEstateName(attendanceGroup.getEstateName());
                    }else {
                        groupUser.setEstateName("未绑定小区");
                    }
                    groupUser.setUserId(0);
                    groupUser.setUserType(1);
                    groupUser.setSysUserId(user.getUserId());
                    groupUser.setState(1);
                    groupUser.setIsCheckHoliday(0);
                    QueryWrapper<AttendanceGroupUser> qw =new QueryWrapper<>();
                    qw.eq("sys_user_id",user.getUserId());
                    List<AttendanceGroupUser> user2=attendanceGroupUserService.list(qw);
                    if (user2 != null){
                        groupUser.setIsDefault(0);
                    }else {
                        groupUser.setIsDefault(1);
                    }
                    AttendanceGroup group1 = attendanceGroupService.selectByUniqueColumn("group_name",attendanceGroup.getGroupName());
                    groupUser.setGroupId(group1.getId());
                    if (attendanceGroup.getIsDefault() != null){
                        groupUser.setIsDefault(attendanceGroup.getIsDefault());
                    }
                    boolean pd2 = attendanceGroupUserService.save(groupUser);
                    if (!pd2){
                        return R.failed("用户'" + groupUser.getSysUserId() + "'添加失败");
                    }
                }
            }
        }
        return R.okByRow(attendanceGroupService.updateById(attendanceGroup) ? 1 : 0);
    }

    /**
     * 删除考勤组
     */
    @ApiOperation("删除考勤组")
    @PreAuthorize("@pms.hasPermission('module:attendanceGroup:remove')")
    @SysLog("考勤组")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(attendanceGroupService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
